package com.ants.boot.core.security.handle;

import com.alibaba.fastjson.JSONObject;
import com.ants.boot.core.enums.SysLoginLogStatusEnum;
import com.ants.boot.core.security.RequestJwtAuthenticationFilter;
import com.ants.boot.system.service.SysLoginLogService;
import com.ants.boot.utils.LoginLogUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Service;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 蚂蚁会花呗
 * @date 2022/2/16 9:56
 */
@Service
public class LoginFailureHandler implements AuthenticationFailureHandler {

    /**
     * 设置request attribute 登录账户
     */
    private static final String REQUEST_LOGIN_USER_ATTRIBUTE = "LOGIN_USER";

    Log logger = LogFactory.getLog(RequestJwtAuthenticationFilter.class);

    @Autowired
    private SysLoginLogService sysLoginLogService;


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.error(exception.getMessage());
        Object loginUser = request.getAttribute(REQUEST_LOGIN_USER_ATTRIBUTE);
        if (loginUser != null){
            LoginLogUtils.addLoginLog(request,sysLoginLogService,loginUser.toString(), SysLoginLogStatusEnum.FAILED.getValue(),exception.getMessage());
        }
        writeResult(response,exception.getMessage());
    }

    /**
     * 返回json结果
     * @param response
     * @param msg
     * @throws IOException
     */
    private void writeResult(HttpServletResponse response,String msg) throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("data","");
        map.put("msg",msg + "！");
        writer.write(JSONObject.toJSONString(map));
    }

}
